package nina.yiyou.performance.s20confirm.input

import nina.yiyou.salary.input.util.CellValueGetter
import nina.yiyou.salary.input.util.ExcelReadOpener
import nina.yiyou.salary.input.util.HeaderMapMaker
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook

import java.util.stream.IntStream
import java.util.stream.Stream

import static java.util.stream.Collectors.toMap

/**
 * 基本信息改由从花名册表读取
 */
class BasicExcelReaderV2 {

  BasicExcelReaderV2(String basicPath) {
    _basicPath = basicPath
  }

  Map<String, Map> read() {
    Workbook workbook = new ExcelReadOpener(_basicPath).openXlsx()
    Map result = readEmployeeMap(workbook)
    workbook.close()
    return result
  }

  private Map<String, Map> readEmployeeMap(Workbook workbook) {
    Sheet allSheet = workbook.getSheetAt(0)
    Map<Integer, String> header = new HeaderMapMaker(allSheet.getRow(0)).make()

    def getCellVal = { Row r, int c -> new CellValueGetter(r.getCell(c)).get() }
    String idKey = header[0]

    return rowStream(allSheet, 1)
        .map { header.collectEntries { col, head -> [head, getCellVal(it, col)] } as Map }
        .collect(toMap({ it[idKey] }, { it }))
  }

  private Stream<Row> rowStream(Sheet sheet, int startRow) {
    return IntStream.rangeClosed(startRow, sheet.lastRowNum)
        .mapToObj { sheet.getRow(it) }
  }

  private final String _basicPath
}
